# -*- coding: utf-8 -*- 
'''
Created on 2011-12-23

@author: TOM
'''
from decimal import Decimal
from django.core import serializers
from django.db.models import Q
from django.http import HttpResponse, HttpResponseNotModified
from django.utils.simplejson import dumps, JSONEncoder
from django.views.decorators.csrf import csrf_exempt
from website import utils, grids
from website.common import getCompanyTuple, getCURoleId, getEmployeId
from website.constant import SUPER_POWER
from website.customercontrol.models import Student, StudentVisit, StudentTrack, \
    TrainingContract, TrainingContractDetail, TrainingContractMans, StudentResource, \
    StudentResourceVisit, StudentHotline
from website.employecontrol.models import Employe
from website.resourcecontrol.models import Grade, Course, Company, \
    CourseCurrentRecord
import time


#@csrf_exempt
#def employe_select(request):
#    data=[{'id':'1','name':'test1'},{'id':'2','name':'test2'}]
#    return HttpResponse(dumps(data))

@csrf_exempt
def grade_select(request):
    results=Grade.objects.all().values()
    return utils.JsonResponse(dumps(list(results)))


@csrf_exempt
def course_select(request):
    q = Q(course_type=1)
    q |= Q(course_type=2)
    results=Course.objects.filter(q).values()
    return utils.JsonResponse(dumps(list(results)))

@csrf_exempt
def queryCourse(request):
    results=Course.objects.all().values()
    return utils.JsonResponse(dumps(list(results)))

#@csrf_exempt
#def queryCourseFee(request):
#    coursefees=CourseFee.objects.all()
#    results=[]
#    for coursefee in coursefees:
#        obj={}
#        obj['course_id']=coursefee.course.id
#        obj['course_name']=coursefee.course.name
#        obj['grade_id']=coursefee.grade.id
#        obj['grade_name']=coursefee.grade.name
#        obj['price']=str(coursefee.price)
#        obj['period']=str(coursefee.period)
#        obj['discount']=str(coursefee.discount)
#        results.append(obj)
#        
#    return HttpResponse(dumps({'success':'true','rows':results}))
#
#@csrf_exempt
#def saveCourseFee(request):
#    try:
#        grade_id=request.POST.get('grade', '')
#        course_id=request.POST.get('course', '')
#        price=request.POST.get('price', '')
#        period=request.POST.get('period', '0')
#        discount=request.POST.get('discount', '0')
#        try:
#            cf=CourseFee.objects.get(course=course_id,grade=grade_id)
#            cf.price=price
#            cf.period=period
#            cf.discount=discount
#            cf.save()
#        except:
#            CourseFee.objects.create(price=price,period=period,discount=discount,course_id=course_id,grade_id=grade_id)   
#    except:
#        return HttpResponse(dumps({'success':False,'message':'失败！'}))
#    return HttpResponse(dumps({'success':True,'message':'成功！'}))


# 学生资源基本信息
@csrf_exempt
def student_resource_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    name=request.POST.get('name','')
    deal_state=request.POST.get('deal_state','')

    q = Q(t=getEmployeId(request))
    if name <>'':
        q &= Q(d__contains=name)
    if deal_state <>'':
        q &= Q(w=deal_state)

    queryset=StudentResource.objects.filter(q);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','a','b','c','d','e','f','g','h','i','j','k',
                                                                 'l','m','n','o','p','q','r','s','t_id','t__name','u','v','w'
                                                                 )), queryset.count()))


@csrf_exempt
def student_resource_update_state(request):
    #修改资源学生的 处理状态及备注
    student_id=request.POST.get('id','')
    deal_state=request.POST.get('w','')
    remark=request.POST.get('u','')
    try:
        student=StudentResource.objects.get(id=student_id)
        student.w=deal_state
        student.u=remark
        student.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def student_resource_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            student_ids=ids.rstrip(',').split(',')
            for student_id in student_ids:
                print student_id
                StudentResource.objects.get(id=student_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))


# 学生资源基本信息回访
@csrf_exempt
def student_resource_visit_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    srid=request.POST.get('student_resource_id','')
    
    queryset=StudentResourceVisit.objects.filter(student_resource=srid);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id', 'student_resource', 'at_time', 'content', 'remark')), queryset.count()))


@csrf_exempt
def student_resource_visit_save(request):
    srv_id=request.POST.get('id','')
    student_resource_id=request.POST.get('student_resource_id','')
    at_time=request.POST.get('at_time','')
    content=request.POST.get('content','')
    remark=request.POST.get('remark','')
    try:
        if srv_id=='':
            StudentResourceVisit.objects.create(student_resource_id=student_resource_id,at_time=at_time,content=content,remark=remark)
        else:
            srv=StudentResourceVisit.objects.get(id=srv_id)
            srv.student_resource_id=student_resource_id
            srv.at_time=at_time
            srv.content=content
            srv.remark=remark
            srv.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def student_resource_visit_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            srv_ids=ids.rstrip(',').split(',')
            for srv_id in srv_ids:
                print srv_id
                StudentResourceVisit.objects.get(id=srv_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))




# 学生基本信息
@csrf_exempt
def company_student_select(request):
    #过滤校区学生 contract
    query=request.POST.get('query','')# 下拉框LIKE查询
    company_id=request.POST.get('company_id','')
    
    q=Q(student_state=1)
    if query != '':
        q &=Q(name__contains=query)
    if company_id !='':
        q &=Q(company=company_id)
    
    results=Student.objects.filter(q).values('id','name')
    return utils.JsonResponse(dumps(list(results)))


@csrf_exempt
def contract_student_select(request):
    #TODO 过滤签约学生 contract
    query=request.POST.get('query','')
    
    q=Q(student_state=1)
    if query != '':
        q &=Q(name__contains=query)   
    results=Student.objects.filter(q).values('id','name')
    return utils.JsonResponse(dumps(list(results)))




@csrf_exempt
def student_hotline_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    name=request.POST.get('name','')
    company_id=request.POST.get('company_id','')
    
    q = Q()
    if getCURoleId(request) <> SUPER_POWER :
        q &=Q(employe=getEmployeId(request))
    if company_id <>'' :
        q &=Q(company=company_id);
    if name <>'' :
        q &=Q(name__contains=name);
    
    queryset=StudentHotline.objects.filter(q);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id', 'name', 'sex','school','grade_id','grade__name','company_id',
                                                                 'company__cn_name','guardian_name','guardian_addr','rela_mobile',
                                                                 'at_time','talk_time','employe_id','employe__name','source','come_time',
                                                                 'remark')), queryset.count()))



@csrf_exempt
def student_hotline_save(request):
    student_id=request.POST.get('id','')
    name=request.POST.get('name','')
    sex=request.POST.get('sex','')
    school=request.POST.get('school','')
    grade_id=request.POST.get('grade_id','')
    company_id=request.POST.get('company_id','')
    guardian_name=request.POST.get('guardian_name','')
    guardian_addr=request.POST.get('guardian_addr','')
    rela_mobile=request.POST.get('rela_mobile','')
    at_time=request.POST.get('at_time','')
    talk_time=request.POST.get('talk_time','')
    employe_id=getEmployeId(request) ;
    source=request.POST.get('source','')
    come_time=request.POST.get('come_time','')
    remark=request.POST.get('remark','')
    
    try:
        if student_id=='':
            StudentHotline.objects.create(name=name, sex=sex, school=school,grade_id=grade_id,company_id=company_id,guardian_name=guardian_name,
                                   guardian_addr=guardian_addr,rela_mobile=rela_mobile,at_time=at_time,talk_time=talk_time,employe_id=employe_id,
                                   source=source,come_time=come_time,remark=remark)
        else:
            student=StudentHotline.objects.get(id=student_id)
            student.name=name
            student.sex=sex
            student.school=school
            student.grade_id=grade_id
            student.company_id=company_id
            student.guardian_name=guardian_name
            student.guardian_addr=guardian_addr
            student.rela_mobile=rela_mobile
            student.at_time=at_time
            student.talk_time=talk_time
            student.employe_id=employe_id
            student.source=source
            student.come_time=come_time
            student.remark=remark
            student.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def student_hotline_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            student_ids=ids.rstrip(',').split(',')
            for student_id in student_ids:
                print student_id
                StudentHotline.objects.get(id=student_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))




@csrf_exempt
def student_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    name=request.POST.get('name','')
    state=request.POST.get('state','')
    
#    if getCURoleId(request) ==SUPER_POWER :
#        company_id=request.POST.get('company_id','')
#    else:
#        company_id = getCompanyTuple(request)[0]
    company_id=request.POST.get('company_id','')
    
    
    q = Q()
    if name !='' :
        q &=Q(name__contains=name)
    if state !='' :
        q &=Q(student_state=state)
    if company_id!='':
        q &=Q(company=company_id)
        
    queryset=Student.objects.filter(q) ;
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id', 'name', 'sex', 'birthday', 'school','grade_id', 'grade__name', 'health', 'relationship',
                                                                 'company_id','company__cn_name' ,
                                                                 'guardian_name', 'guardian_cardno', 'guardian_phone', 'guardian_addr', 
                                                                 'guardian_mobile', 'guardian_qq', 'class_ranking', 'school_ranking', 
                                                                 'exam_time', 'yw', 'sx', 'yy', 'wl', 'hx', 'sw', 'ls', 'zz', 'dl', 
                                                                 'student_state','student_manager_id','student_manager__name',
                                                                 'call_man_id','call_man__name','provide_man_id','provide_man__name','remark')), queryset.count()))



@csrf_exempt
def student_save(request):
    student_id=request.POST.get('id','')
    name=request.POST.get('name','')
    sex=request.POST.get('sex','1')
    birthday=request.POST.get('birthday','')
    school=request.POST.get('school','')
    grade=request.POST.get('grade_id','')
    health=request.POST.get('health','')
    relationship=request.POST.get('relationship','')
    company_id=request.POST.get('company_id','')    
    guardian_name=request.POST.get('guardian_name','')
    guardian_cardno=request.POST.get('guardian_cardno','')
    guardian_phone=request.POST.get('guardian_phone','')
    guardian_addr=request.POST.get('guardian_addr','')
    guardian_mobile=request.POST.get('guardian_mobile','')
    guardian_qq=request.POST.get('guardian_qq','')
    class_ranking=request.POST.get('class_ranking','')
    school_ranking=request.POST.get('school_ranking','')
    exam_time=request.POST.get('exam_time','')
    yw=request.POST.get('yw','')
    sx=request.POST.get('sx','')
    yy=request.POST.get('yy','')
    wl=request.POST.get('wl','')
    hx=request.POST.get('hx','')
    sw=request.POST.get('sw','')
    ls=request.POST.get('ls','')
    zz=request.POST.get('zz','')
    dl=request.POST.get('dl','')
    student_state=request.POST.get('student_state','1')
    student_manager_id=request.POST.get('student_manager_id','1')
    call_man_id=request.POST.get('call_man_id','')
    provide_man_id=request.POST.get('provide_man_id','')
    remark=request.POST.get('remark','')
    try:
        if student_id=='':
            Student.objects.create(name=name, sex=sex, birthday=birthday, school=school, grade_id=grade, health=health, relationship=relationship,
                                   company_id=company_id,
                                   guardian_name=guardian_name, guardian_cardno=guardian_cardno, guardian_phone=guardian_phone,
                                   guardian_addr=guardian_addr, guardian_mobile=guardian_mobile, guardian_qq=guardian_qq, class_ranking=class_ranking,
                                   school_ranking=school_ranking, exam_time=exam_time, yw=yw, sx=sx, yy=yy, wl=wl, hx=hx, sw=sw, ls=ls, zz=zz, dl=dl, 
                                   student_state=student_state,student_manager_id=student_manager_id, call_man_id=call_man_id,provide_man_id=provide_man_id,remark=remark,current_time=time.strftime('%Y-%m-%d',time.localtime(time.time())))
        else:
            student=Student.objects.get(id=student_id)
            student.name=name
            student.sex=sex
            student.birthday=birthday
            student.school=school
            student.grade_id=grade
            student.health=health
            student.relationship=relationship
            student.company_id=company_id
            student.guardian_name=guardian_name
            student.guardian_cardno=guardian_cardno
            student.guardian_phone=guardian_phone
            student.guardian_addr=guardian_addr
            student.guardian_mobile=guardian_mobile
            student.guardian_qq=guardian_qq
            student.class_ranking=class_ranking
            student.school_ranking=school_ranking
            student.exam_time=exam_time
            student.yw=yw
            student.sx=sx
            student.yy=yy
            student.wl=wl
            student.hx=hx
            student.sw=sw
            student.ls=ls
            student.zz=zz
            student.dl=dl
            student.student_state=student_state
            student.student_manager_id=student_manager_id
            student.call_man_id=call_man_id
            student.provide_man_id=provide_man_id
            student.remark=remark
            #student.current_time=time.strftime('%Y-%m-%d',time.localtime(time.time()))
            student.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def student_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            student_ids=ids.rstrip(',').split(',')
            for student_id in student_ids:
                Student.objects.get(id=student_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))





# 学生合同
@csrf_exempt
def training_contract_list_query(request):
    start=request.POST['start']
    limit=request.POST['limit']
    student_id=request.POST.get('student_id','')
    state=request.POST.get('state','')
    state_notin=request.POST.get('state_notin','')
    student_name=request.POST.get('student_name','')
    
    if getCURoleId(request) ==SUPER_POWER :
        company_id=request.POST.get('company_id','')
    else:
        company_id = getCompanyTuple(request)[0]
    
    school=Company.objects.get(id=company_id)
    if student_name <> '':
        q=Q(student__in=school.student_school.filter(name__contains=student_name))
    else:
        q=Q(student__in=school.student_school.all())
    
    if student_id <>'':
        q &=Q(student=student_id)
    if state <>'':
        q &=Q(state=state)
    if state_notin <>'':
        q &=~Q(state=state_notin)

    
    queryset=TrainingContract.objects.filter(q)
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','name', 'student_id','student__name','service_fee','education_fee','traffic_fee',
                                                                 'service_fee_pay','education_fee_pay','traffic_fee_pay',
                                                                 'service_fee_card','education_fee_card','traffic_fee_card',
                                                                 'education_ratio','tran_type','tran_num',
                                                                 'tran_last','contract_type','begin_time','end_time','finish_time','state','audit_man_id','audit_man__name','audit_remark',
                                                                 'finance_audit_man_id','finance_audit_man__name','finance_audit_remark','remark','entering_man__name')), queryset.count()))
 
 
@csrf_exempt
def training_contract_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    student_id=request.POST.get('student_id','')
    state=request.POST.get('state','')
    state_notin=request.POST.get('state_notin','')
    student_name=request.POST.get('student_name','')
    company_id=request.POST.get('company_id','')
#    if getCURoleId(request) ==SUPER_POWER :
#        company_id=request.POST.get('company_id','')
#    else:
#        company_id = getCompanyTuple(request)[0]
    
    if company_id <> '':
        school=Company.objects.get(id=company_id)
        if student_name <> '':
            q=Q(student__in=school.student_school.filter(name__contains=student_name))
        else:
            q=Q(student__in=school.student_school.all())
    else:
        if student_name <> '':
            q=Q(student__name__contains=student_name)
        else:
            q=Q()
    
    if student_id <>'':
        q &=Q(student=student_id)
    if state <>'':
        q &=Q(state=state)
    if state_notin <>'':
        q &=~Q(state=state_notin)
    
    # 资讯师查自己的
    employeId = getEmployeId(request) 
    employe = Employe.objects.get(id=employeId) 
    if employe.office.id  in (43,21)  :
        q &=Q(entering_man=employeId)
        
    
    queryset=TrainingContract.objects.filter(q)
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','name', 'student_id','student__name','service_fee','education_fee','traffic_fee',
                                                                 'service_fee_pay','education_fee_pay','traffic_fee_pay',
                                                                 'service_fee_card','education_fee_card','traffic_fee_card',
                                                                 'education_ratio','tran_type','tran_num',
                                                                 'tran_last','contract_type','begin_time','end_time','finish_time','state','audit_man_id','audit_man__name','audit_remark',
                                                                 'finance_audit_man_id','finance_audit_man__name','finance_audit_remark','remark','student__company__cn_name','entering_man__name')), queryset.count()))

# 合同预制界面，专用
@csrf_exempt
def training_contract_list_yz(request):
    start=request.POST['start']
    limit=request.POST['limit']
    student_id=request.POST.get('student_id','')
    state=request.POST.get('state','')
    state_notin=request.POST.get('state_notin','')
    student_name=request.POST.get('student_name','')
    company_id=request.POST.get('company_id','')
    entering_man=getEmployeId(request) ;
#    if getCURoleId(request) ==SUPER_POWER :
#        company_id=request.POST.get('company_id','')
#    else:
#        company_id = getCompanyTuple(request)[0]
    
    if company_id <> '':
        school=Company.objects.get(id=company_id)
        if student_name <> '':
            q=Q(student__in=school.student_school.filter(name__contains=student_name))
        else:
            q=Q(student__in=school.student_school.all())
    else:
        if student_name <> '':
            q=Q(student__name__contains=student_name)
        else:
            q=Q()
    
    if student_id <>'':
        q &=Q(student=student_id)
    if state <>'':
        q &=Q(state='0')
        q |=Q(state='6')
    if state_notin <>'':
        q &=~Q(state=state_notin)
        q &=~Q(state='0')
        q &=~Q(state='6')
    
    q &=Q(entering_man=entering_man)
    
    queryset=TrainingContract.objects.filter(q)
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','name', 'student_id','student__name','service_fee','education_fee','traffic_fee',
                                                                 'service_fee_pay','education_fee_pay','traffic_fee_pay',
                                                                 'service_fee_card','education_fee_card','traffic_fee_card',
                                                                 'education_ratio','tran_type','tran_num',
                                                                 'tran_last','contract_type','begin_time','end_time','finish_time','state','audit_man_id','audit_man__name','audit_remark',
                                                                 'finance_audit_man_id','finance_audit_man__name','finance_audit_remark','remark','student__company__cn_name','entering_man__name')), queryset.count()))
    

@csrf_exempt
def training_contract_find(request):
    # 获取条件下所有合同
    student_id=request.POST.get('student_id','')
    
    if student_id <>'':
        q = Q(student=student_id)
        
    queryset=TrainingContract.objects.filter(q).values('id','state')
    return utils.JsonResponse(dumps(list(queryset)))


@csrf_exempt
def training_contract_get(request):
    # 获取指定ID合同
    cid=request.POST.get('cid','')
    results=TrainingContract.objects.filter(id=cid).values('id','state');
    return utils.JsonResponse(dumps(list(results)))





# 普通员工预置合同
@csrf_exempt
def training_contract_save(request):
    training_contract_id=request.POST.get('id','')
    name=request.POST.get('name','')
    student_id=request.POST.get('student_id','')
    service_fee=request.POST.get('service_fee','')
    education_fee=request.POST.get('education_fee','')
    traffic_fee=request.POST.get('traffic_fee','')
    service_fee_pay=request.POST.get('service_fee_pay','')
    education_fee_pay=request.POST.get('education_fee_pay','')
    traffic_fee_pay=request.POST.get('traffic_fee_pay','')
    service_fee_card=request.POST.get('service_fee_card','')
    education_fee_card=request.POST.get('education_fee_card','')
    traffic_fee_card=request.POST.get('traffic_fee_card','')
    if  education_fee=='0':
        return HttpResponse(dumps({'success':False,'message':'教育咨询费不可为零!'}))
    
    education_ratio = (Decimal(education_fee_pay)+Decimal(education_fee_card))/Decimal(education_fee)
    tran_type=request.POST.get('tran_type','')
    tran_num=request.POST.get('tran_num','')
    tran_last=request.POST.get('tran_last','')
    begin_time=request.POST.get('begin_time','')
    end_time=request.POST.get('end_time','')
    finish_time=request.POST.get('finish_time','')
    contract_type=request.POST.get('contract_type','')
    state=request.POST.get('state','0')#预制状态
    remark=request.POST.get('remark','')
    is_like=request.POST.get('is_like','')#是否参照 1是
    like_id=request.POST.get('like_id','')#参照合同ID
    entering_man=getEmployeId(request) ;

    try:
        if training_contract_id=='':
            tc = TrainingContract.objects.create(name=name,student_id=student_id,service_fee=service_fee, education_fee=education_fee, traffic_fee=traffic_fee,
                                   service_fee_pay=service_fee_pay, education_fee_pay=education_fee_pay, traffic_fee_pay=traffic_fee_pay,
                                   service_fee_card=service_fee_card, education_fee_card=education_fee_card, traffic_fee_card=traffic_fee_card,
                                   education_ratio=education_ratio,
                                   tran_type=tran_type, tran_num=tran_num, tran_last=tran_last, begin_time=begin_time, end_time=end_time,
                                   finish_time=finish_time,contract_type=contract_type, state=state, remark=remark,entering_man_id=entering_man)
        else:
            training_contract=TrainingContract.objects.get(id=training_contract_id)
            training_contract.name=name
            training_contract.student_id=student_id
            training_contract.service_fee=service_fee
            training_contract.education_fee=education_fee
            training_contract.traffic_fee=traffic_fee
            training_contract.service_fee_pay=service_fee_pay
            training_contract.education_fee_pay=education_fee_pay
            training_contract.traffic_fee_pay=traffic_fee_pay
            training_contract.service_fee_card=service_fee_card
            training_contract.education_fee_card=education_fee_card
            training_contract.traffic_fee_card=traffic_fee_card
            training_contract.education_ratio=education_ratio
            training_contract.tran_type=tran_type
            training_contract.tran_num=tran_num
            training_contract.tran_last=tran_last
            training_contract.begin_time=begin_time
            training_contract.end_time=end_time
            training_contract.finish_time=finish_time
            training_contract.contract_type=contract_type
            training_contract.state=state
            training_contract.remark=remark
            training_contract.entering_man_id=entering_man
            training_contract.save()
            
        
        #参照功能：增加原合同的明细和签订人
        if is_like=='1':
            queryset=TrainingContractDetail.objects.filter(training_contract=like_id)
            for qs in queryset:
                TrainingContractDetail.objects.create(training_contract_id=tc.id,grade_id=qs.grade_id,course_id=qs.course_id,
                                                  study_type=qs.study_type,course_times=qs.course_times,old_price=qs.old_price,
                                                  current_price=qs.current_price,total_prices=qs.total_prices,pay_prices=qs.pay_prices,
                                                  pay_card_prices=qs.pay_card_prices,course_times_week=qs.course_times_week)
                
            queryset=TrainingContractMans.objects.filter(training_contract=like_id)
            for qs in queryset:
                TrainingContractMans.objects.create(training_contract_id=tc.id,employe_id=qs.employe_id,ratio=qs.ratio, ret_ratio=qs.ret_ret_ratio)
        
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


# 修改合同状态
@csrf_exempt
def training_contract_update_state0(request):
    # 员工提交
    training_contract_id=request.POST.get('training_contract_id','')
    state=request.POST.get('state','')
    remark=request.POST.get('remark','')
    employe_id=getEmployeId(request) ;
    try:
        training_contract=TrainingContract.objects.get(id=training_contract_id)
        training_contract.state=state
        training_contract.remark=remark
        training_contract.create_man_id=employe_id
        training_contract.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'操作成功！'}))

 
# 修改合同状态
@csrf_exempt
def training_contract_update_state(request):
    # 主管审核
    training_contract_id=request.POST.get('training_contract_id','')
    state=request.POST.get('state','')
    audit_remark=request.POST.get('audit_remark','')
    employe_id=getEmployeId(request) ;
    try:
        training_contract=TrainingContract.objects.get(id=training_contract_id)
        training_contract.state=state
        training_contract.audit_remark=audit_remark
        training_contract.audit_man_id=employe_id
        training_contract.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'操作成功！'})) 
     
# 修改合同状态
@csrf_exempt
def training_contract_update_state2(request):
    # 账务审核
    training_contract_id=request.POST.get('training_contract_id','')
    state=request.POST.get('state','')
    finance_audit_remark=request.POST.get('finance_audit_remark','')
    employe_id=getEmployeId(request) ;
    
    
    # 保存课时
    if state == '1':
        tc=TrainingContract.objects.get(id=training_contract_id)
#        tc.end_time = time.strftime('%Y-%m-%d',time.localtime(time.time()))
#        tc.save()
        details=TrainingContractDetail.objects.filter(training_contract=training_contract_id)
        for detail in details:
            try:
                ccr=CourseCurrentRecord.objects.get(student=tc.student_id,grade=detail.grade_id,course=detail.course_id,study_type=detail.study_type)
                ccr.course_times=Decimal(ccr.course_times) + Decimal(detail.course_times)
                ccr.save()
            except Exception,ex:
                CourseCurrentRecord.objects.create(student_id=tc.student_id,grade_id=detail.grade_id,course_id=detail.course_id,study_type=detail.study_type,course_times=detail.course_times,use_course_times=0)
            
    try:
        training_contract=TrainingContract.objects.get(id=training_contract_id)
        training_contract.state=state
        training_contract.finance_audit_remark=finance_audit_remark
        training_contract.finance_audit_man_id=employe_id
        training_contract.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'操作成功！'})) 
     
   



@csrf_exempt
def training_contract_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            training_contract_ids=ids.rstrip(',').split(',')
            for training_contract_id in training_contract_ids:
                TrainingContract.objects.get(id=training_contract_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))



# 学生合同明细
@csrf_exempt
def training_contract_detail_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    detail_id=request.POST.get('training_contract_id','')
    if detail_id =='':
        queryset=TrainingContractDetail.objects.filter();
    else:
        queryset=TrainingContractDetail.objects.filter(training_contract=detail_id);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id', 'training_contract_id','grade_id','grade__name','course_id',
                                                                 'course__name','study_type','course_times','old_price','current_price','rebate',
                                                                 'total_prices','pay_prices','pay_card_prices','course_times_week')), queryset.count()))



@csrf_exempt
def training_contract_detail_save(request):
    detail_id=request.POST.get('id','')
    training_contract_id=request.POST.get('training_contract_id','')
    grade_id=request.POST.get('grade_id','')
    course_id=request.POST.get('course_id','')
    study_type=request.POST.get('study_type','')
    course_times=request.POST.get('course_times','')
    old_price=request.POST.get('old_price','')
    current_price=request.POST.get('current_price','')
    rebate = (Decimal(current_price))/Decimal(old_price)#折扣
    total_prices=Decimal(course_times)*Decimal(current_price)
    pay_prices=request.POST.get('pay_prices','')
    pay_card_prices=request.POST.get('pay_card_prices','')
    course_times_week=request.POST.get('course_times_week','')
   
    try:
        if detail_id=='':
            TrainingContractDetail.objects.create(training_contract_id=training_contract_id,grade_id=grade_id,course_id=course_id,
                                                  study_type=study_type,course_times=course_times,old_price=old_price,
                                                  current_price=current_price,rebate=rebate,total_prices=total_prices,pay_prices=pay_prices,
                                                  pay_card_prices=pay_card_prices,course_times_week=course_times_week)
        else:
            training_contract_detail=TrainingContractDetail.objects.get(id=detail_id)
            training_contract_detail.training_contract_id=training_contract_id
            training_contract_detail.grade_id=grade_id
            training_contract_detail.course_id=course_id
            training_contract_detail.study_type=study_type
            training_contract_detail.course_times=course_times
            training_contract_detail.old_price=old_price
            training_contract_detail.current_price=current_price
            training_contract_detail.rebate=rebate
            training_contract_detail.total_prices=total_prices
            training_contract_detail.pay_prices=pay_prices
            training_contract_detail.pay_card_prices=pay_card_prices
            training_contract_detail.course_times_week=course_times_week
            training_contract_detail.save()
            
#        training_contract_pay_detail_save(request) ;
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def training_contract_detail_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            detail_ids=ids.rstrip(',').split(',')
            for detail_id in detail_ids:
                TrainingContractDetail.objects.get(id=detail_id).delete()
                
#        training_contract_pay_detail_del(request)
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))

## 学生合同付款明细
#@csrf_exempt
#def training_contract_pay_detail_list(request):
#    start=request.POST['start']
#    limit=request.POST['limit']
#    detail_id=request.POST.get('training_contract_id','')
#    if detail_id =='':
#        queryset=TrainingContractPayDetail.objects.filter();
#    else:
#        queryset=TrainingContractPayDetail.objects.filter(training_contract=detail_id);
#    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
#        list(queryset[int(start):int(start) + int(limit)].values('id', 'training_contract_id','course_id','study_type',
#                                                                 'course__name','total_prices','pay_card_prices','pay_prices')), queryset.count()))
#
#@csrf_exempt
#def training_contract_pay_detail_save(request):
#    detail_id=request.POST.get('id','')
#    training_contract_id=request.POST.get('training_contract_id','')
#    course_id=request.POST.get('course_id','')
#    study_type=request.POST.get('study_type','')
#    total_prices=request.POST.get('total_prices','')
#    pay_prices=request.POST.get('pay_prices','')
#    pay_card_prices=request.POST.get('pay_card_prices','')
#   
#    try:
#        if detail_id=='':
#            TrainingContractPayDetail.objects.create(training_contract_id=training_contract_id,course_id=course_id,study_type=study_type,
#                                                  total_prices=total_prices,pay_prices=pay_prices,pay_card_prices=pay_card_prices)
#        else:
#            training_contract_detail=TrainingContractPayDetail.objects.get(id=detail_id)
#            training_contract_detail.training_contract_id=training_contract_id
#            training_contract_detail.course_id=course_id
#            training_contract_detail.study_type=study_type
#            training_contract_detail.total_prices=total_prices
#            training_contract_detail.pay_prices=pay_prices
#            training_contract_detail.pay_card_prices=pay_card_prices
#            training_contract_detail.save()
#    except Exception,ex:
#        print ex
#        return HttpResponse(dumps({'success':False,'message':str(ex)}))
#    return HttpResponse(dumps({'success':True,'message':'成功！'}))
#
#
#@csrf_exempt
#def training_contract_pay_detail_del(request):
#    try:
#        ids=request.POST.get('ids','')
#
#        if ids <> '':
#            detail_ids=ids.rstrip(',').split(',')
#            for detail_id in detail_ids:
#                TrainingContractPayDetail.objects.get(id=detail_id).delete()
#    except Exception,ex:
#        return HttpResponse(dumps({'success':False,'message':str(ex)}))
#    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))



# 学生合同签定人信息
@csrf_exempt
def training_contract_mans_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    mans_id=request.POST.get('training_contract_id','')
    if mans_id =='':
        queryset=TrainingContractMans.objects.filter();
    else:
        queryset=TrainingContractMans.objects.filter(training_contract=mans_id);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id', 'training_contract_id','employe_id','employe__name','ratio', 'ret_ratio')), queryset.count()))



@csrf_exempt
def training_contract_mans_save(request):
    mans_id=request.POST.get('id','')
    training_contract_id=request.POST.get('training_contract_id','')
    employe_id=request.POST.get('employe_id','')
    ratio=request.POST.get('ratio','')
    ret_ratio=request.POST.get('ret_ratio','')
   
    try:
        if mans_id=='':
            TrainingContractMans.objects.create(training_contract_id=training_contract_id,employe_id=employe_id,ratio=ratio,ret_ratio=ret_ratio)
        else:
            training_contract_mans=TrainingContractMans.objects.get(id=mans_id)
            training_contract_mans.training_contract_id=training_contract_id
            training_contract_mans.employe_id=employe_id
            training_contract_mans.ratio=ratio
            training_contract_mans.ret_ratio=ret_ratio
            training_contract_mans.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def training_contract_mans_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            mans_ids=ids.rstrip(',').split(',')
            for mans_id in mans_ids:
                TrainingContractMans.objects.get(id=mans_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))



#学生回访记录
@csrf_exempt
def student_visit_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    student_id=request.POST.get('student_id','')
    if student_id =='':
        queryset=StudentVisit.objects.filter();
    else:
        queryset=StudentVisit.objects.filter(student=student_id);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id', 'at_time','use_phone','student_id','student__name','parent_name','parent_phone','satisfaction','visit_man_id','visit_man__name', 'remark')), queryset.count()))



@csrf_exempt
def student_visit_save(request):
    student_visit_id=request.POST.get('id','')
    at_time=request.POST.get('at_time','')
    use_phone=request.POST.get('use_phone','')
    student_id=request.POST.get('student_id','')
    parent_name=request.POST.get('parent_name','')
    parent_phone=request.POST.get('parent_phone','')
    satisfaction=request.POST.get('satisfaction','')
    remark=request.POST.get('remark','')
    visit_man_id= getEmployeId(request) ;
    try:
        if student_visit_id=='':
            StudentVisit.objects.create(at_time=at_time,use_phone=use_phone,student_id=student_id,parent_name=parent_name,
                                        parent_phone=parent_phone,satisfaction=satisfaction,visit_man_id=visit_man_id,remark=remark)
        else:
            student_visit=StudentVisit.objects.get(id=student_visit_id)
            student_visit.at_time=at_time
            student_visit.use_phone=use_phone
            student_visit.student_id=student_id
            student_visit.parent_name=parent_name
            student_visit.parent_phone=parent_phone
            student_visit.satisfaction=satisfaction
            student_visit.visit_man_id=visit_man_id
            student_visit.remark=remark
            student_visit.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def student_visit_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            student_visit_ids=ids.rstrip(',').split(',')
            for student_visit_id in student_visit_ids:
                StudentVisit.objects.get(id=student_visit_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))






#学生课后跟踪
@csrf_exempt
def student_track_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    student_id=request.POST.get('student_id','')
    if student_id =='':
        queryset=StudentTrack.objects.filter();
    else:
        queryset=StudentTrack.objects.filter(student=student_id);
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id', 'at_time','student_id','student__name','track_1','track_2','track_3', 'remark')), queryset.count()))



@csrf_exempt
def student_track_save(request):
    student_track_id=request.POST.get('id','')
    at_time=request.POST.get('at_time','')
    student_id=request.POST.get('student_id','')
    track_1=request.POST.get('track_1','')
    track_2=request.POST.get('track_2','')
    track_3=request.POST.get('track_3','')
    remark=request.POST.get('remark','')
    try:
        if student_track_id=='':
            StudentTrack.objects.create(at_time=at_time,student_id=student_id,track_1=track_1,
                                        track_2=track_2,track_3=track_3,remark=remark)
        else:
            student_track=StudentTrack.objects.get(id=student_track_id)
            student_track.at_time=at_time
            student_track.student_id=student_id
            student_track.track_1=track_1
            student_track.track_2=track_2
            student_track.track_3=track_3
            student_track.remark=remark
            student_track.save()
    except Exception,ex:
        print ex
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def student_track_del(request):
    try:
        ids=request.POST.get('ids','')

        if ids <> '':
            student_track_ids=ids.rstrip(',').split(',')
            for student_track_id in student_track_ids:
                StudentTrack.objects.get(id=student_track_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))
